﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Linq.Expressions;
using Mall.Infrastructure.EnityFramework;

namespace Mall.Infrastructure.Repository
{
    internal class EdmRepository<TEntity> : IRepository<TEntity> where TEntity :class
    {
        #region Private Fields
        private readonly ObjectContext objContext;
        private readonly string entitySetName;
        private readonly ObjectSet<TEntity> set;
        #endregion

        #region Constructors
        /// <summary>
        /// 
        /// </summary>
        /// <param name="objContext"></param>
        public EdmRepository(ObjectContext objContext)
        {
            this.objContext = objContext;
            if (!typeof(TEntity).IsDefined(typeof(EnityNameAttribute), true))
                throw new Exception();
            EnityNameAttribute enityNameAttribute = (EnityNameAttribute)typeof(TEntity)
                .GetCustomAttributes(typeof(EnityNameAttribute), true)[0];
            this.entitySetName = enityNameAttribute.EntityName;
            set=this.objContext.CreateObjectSet<TEntity>();
        }
        #endregion

        #region IRepository<TEntity> Members
        public void Add(TEntity entity)
        {
            this.set.AddObject(entity);
        }

        public void Remove(TEntity entity)
        {
            this.set.DeleteObject(entity);
        }

       
        public int Delete(Expression<Func<TEntity, bool>> predicate)
        {
            return this.set.Delete<TEntity>(predicate);
        }

        public int Update(Expression<Func<TEntity, TEntity>> updater, Expression<Func<TEntity, bool>> where)
        {
            return this.set.Update<TEntity>(updater,where);
        }

        public void Update(TEntity entity)
        {
            //this.set.Update<TEntity>(entity);
        }

        public IQueryable<TEntity> Where(Expression<Func<TEntity, bool>> predicate)
        {
            return set.Where(predicate);  
        }


        public IQueryable<TEntity> Where(Expression<Func<TEntity, int, bool>> predicate)
        {
            return set.Where(predicate);
        }

        public object GetContext()
        {
            return objContext;
        }


        #endregion

        #region Protected Properties
        protected string EntitySetName
        {
            get { return this.entitySetName; }
        }
        protected ObjectContext ObjContext
        {
            get { return this.objContext; }
        }
        #endregion
    }
}
